<template>
  <!-- tab基本信息表单  -->
  <div id="BacCultureCombinationForm">
    <Splitpanes class="area" horizontal>
      <Pane size="36">
        <el-scrollbar style="height:100%;">
          <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80" class="form-input-m" inline-message>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="组合代码" prop="code">
                  <el-input v-model="formData.code" placeholder="请输入组合代码" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="组合名称" prop="name">
                  <el-input v-model="formData.name" style="width:80%;" placeholder="请输入组合名称" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" clearable type="textarea" style="width:80%;"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="组合类别" prop="type">
                  <el-radio-group v-model="formData.type">
                    <el-radio :label="'0'">普通</el-radio>
                    <el-radio :label="'1'">纯分</el-radio>
                    <el-radio :label="'2'">转种</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="录入码" prop="inputCode">
                  <el-input v-model="formData.inputCode" placeholder="请输入录入码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="序号" prop="orderNum">
                  <el-input v-model="formData.orderNum" placeholder="请输入序号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item label="标签份数" prop="tagsNum">
                  <el-input v-model="formData.tagsNum" placeholder="请输入标签份数" clearable></el-input>（0表示按照实际培养基数量打印）
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-scrollbar>
      </Pane>
      <Pane size="54">
        <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" height="auto" :data="formData.cultureRelList" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @cell-click="tableCellClick" show-overflow keep-source>
          <vxe-column field="code" title="编号" width="130">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="formData.code" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="cultrueName" title="培养基" min-width="220" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row }">
              <vxe-select v-model="row.culMediumNo" @change="getMediumName(row, $event)" clearable filterable>
                <vxe-option :value="item.code" :label="item.name" v-for="item in sourcelist" :key="item.id"></vxe-option>
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="orderNum" title="序号" width="220px" :edit-render="{ autofocus: '.vxe-input--inner' }">
            <template #edit="{ row, rowIndex, column }">
              <vxe-input v-model="row.orderNum" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="code" title="初鉴结果默认" width="100">
            <template #default="{ row }">
              <el-switch v-model="row.defaultResult" inline-prompt active-text="是" inactive-text="否"></el-switch>
            </template>
          </vxe-column>
        </vxe-table>
      </Pane>
      <Pane size="10">
        <div class="detailsBtns">
          <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveForm"></vxe-button>
          <vxe-button style="margin-left:10px;" type="text" class="button-blue" icon="vxe-icon-add" content="新增明细" @click="addMx"></vxe-button>
          <vxe-button style="margin-left:10px;" type="text" class="button-blue" icon="vxe-icon-copy" content="插入明细" @click="insertMx"></vxe-button>
          <vxe-button style="margin-left:10px;" type="text" class="button-red" icon="vxe-icon-delete" content="删除明细" @click="deleteMx"></vxe-button>
        </div>
      </Pane>
      <!-- 配置扩展属性弹框 -->
      <!-- <EditExtraProperties ref="EditExtraPropertiesRef" /> -->
    </Splitpanes>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { ref, reactive, watch, getCurrentInstance, PropType, onMounted } from 'vue';
import { VXETable, VxeFormPropTypes, VxeButtonEvents } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../utils/CommonMessage';
import { funBdsJsResult } from '../../utils/Expression'; //函数公式
import VxePulldownSelection from '../../components/VxePulldownSelection.vue'; //引用下拉框组件
import EditExtraProperties from '../../components/EditExtraProperties.vue'; //配置扩展属性弹框组件
import SelectDataList from '../../components/SelectDataList.vue';
import { Splitpanes, Pane } from 'splitpanes';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let sourcelist = reactive([]);
let orderNum = ref(null);
let index = ref(null);
let tableRef = ref(null);

const formRef = ref(); //表单ref标记
// 表单绑定的数据类型限制
interface FormDataVO {
  id: string /*主键*/;
  code: string /*培养基编码*/;
  name: string /*培养基代号*/;
  remark: string /*培养基名称*/;
  type: string /*培养基英文编码*/;
  inputCode: string /*培养基英文名称*/;
  orderNum: string /*输入码*/;
  tagsNum: any /*标签分数*/;
  orgId: string /*标准名称*/;
  cultureRelList: Array;
}
// 表单绑定的数据
let formData = reactive<FormDataVO>({
  id: '' /*主键*/,
  code: '' /*培养基编码*/,
  name: '' /*培养基代号*/,
  remark: '' /*培养基名称*/,
  type: '' /*培养基英文编码*/,
  inputCode: '' /*培养基英文名称*/,
  orderNum: '' /*输入码*/,
  tagsNum: null /*标签分数*/,
  orgId: '' /*标准名称*/,
  cultureRelList: reactive([])
});

// 表单校验规则
const formRules = reactive<VxeFormPropTypes.Rules>({
  code: [{ required: true, message: '请输入编码' }],
  name: [{ required: true, message: '请输入名称' }]
});

const EditExtraPropertiesRef = ref(null); //配置扩展属性弹框ref
// const collapseStatus = ref(false);

defineExpose({
  addNew,
  saveForm,
  clearFormData,
  getRowList
});

onMounted(() => {
  findcultureRelList(); // 获取培养基数据
});
// 获取培养基
const findcultureRelList = () => {
  sourcelist.length = 0; //放入数据前清空数据
  const url = '/api/sta/sta-culture-medium/findBacCultureMediumList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then(async (res: any) => {
      sourcelist.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取培养基数据异常', VxeNotifyType.error);
    });
};

function getRowList(row) {
  Object.assign(formData, row);
  formData.cultureRelList = JSON.parse(JSON.stringify(row.cultureRelList));
  formData.cultureRelList.forEach((element) => {
    element.code = row.code;
  });
  const $table = tableRef.value;
  if ($table) {
    $table.setCurrentRow(formData.cultureRelList[0]);
  }
}

// 方法定义区 =============
function addNew() {
  clearFormData(); // 清空表单
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

// 自动生成助记符
function autoInputCode() {
  formData.inputCode = funBdsJsResult('firstPinYinFun', formData.name);
}

// 清空表单
function clearFormData() {
  formData.id = '';
  formData.code = '';
  formData.name = '';
  formData.remark = '';
  formData.type = '';
  formData.inputCode = '';
  formData.orderNum = '';
  formData.tagsNum = null;
  formData.orgId = '';
  formData.cultureRelList = reactive([]);
}

function addMx() {
  const data = {
    code: formData.code,
    orderNum: formData.cultureRelList.length * 10 + 10
  };
  formData.cultureRelList.push(data);
}
function getMediumName(row, event) {
  row.culMediumNo = event.value;
  const medium = sourcelist.find((item) => item.code === event.value);
  row.cultrueName = medium.name;
}
/**表格选中当前行*/
function tableCellClick({ row }) {
  orderNum.value = row.orderNum;
  index.value = formData.cultureRelList.findIndex((item) => {
    return orderNum.value == item.orderNum;
  });
}
function deleteMx() {
  formData.cultureRelList.splice(index.value, 1);
  let i = 0;
  formData.cultureRelList.forEach((element) => {
    element.orderNum = i * 10 + 10;
    i++;
  });
}
function insertMx() {
  const data = {
    code: formData.code
  };
  let i = 0;
  formData.cultureRelList.splice(index.value, 0, data);
  formData.cultureRelList.forEach((element) => {
    element.orderNum = i * 10 + 10;
    i++;
  });
}

// 保存分管类别
function saveForm(callback: any) {
  const el: any = proxy.$refs['formRef'];
  formRef.value?.validate((valid: any) => {
    if (!valid) {
      VxeMessage('校验表单失败', VxeNotifyType.error);
      return false;
    }
    let url = '';
    // 判断添加和编辑接口
    if (IsEmpty(formData.id)) {
      url = '/api/sta/sta-cultrue-combination/addBacCultureCombination';
    } else {
      url = '/api/sta/sta-cultrue-combination/updateBacCultureCombination';
    }
    proxy.$http
      .post(url, formData)
      .then((res: any) => {
        if (res.status.code === 200) {
          if (!IsEmpty(formData.id)) {
            proxy.$emit('findList');
            VxeMessage('修改培养基成功', VxeNotifyType.success);
          } else {
            proxy.$emit('findList');
            VxeMessage('新增培养基成功', VxeNotifyType.success);
          }
          if (callback) {
            callback(true);
          }
        } else {
          if (!IsEmpty(formData.id)) {
            proxy.$emit('findList');
            VxeMessage(res.status.msg, VxeNotifyType.error);
          } else {
            proxy.$emit('findList');
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
          if (callback) {
            callback(false);
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage('保存分管类别异常', VxeNotifyType.error);
        // if (callback) {
        //   callback(false);
        // }
      });
  });
}
</script>

<style lang="scss" scoped>
#BacCultureCombinationForm {
  height: 100%;
  width: 100%;

  .area {
    height: 100%;

    .el-form {
      padding: 15px;
    }

    .detailsBtns {
      margin: 10px;
    }
  }
}
</style>
